#!/bin/sh

set -ex

# go to builder main directory
cd "$(dirname $0)/.."

# clean env only one chroot
chroot_dir="$(ls -d chroot-* || :)"
if [ -z "$chroot_dir" ]; then
    echo "Nothing was built, skipping install"
    exit
fi
YUM="$(sudo chroot "$chroot_dir" /usr/bin/which dnf || true)"
if [ -z "$YUM" ]; then
    YUM="$(sudo chroot "$chroot_dir" /usr/bin/which yum || true)"
fi

# remove fstab created by chroot builder
# it causes failures in installing (core|gui)-agent-linux
sudo rm -f "$chroot_dir/etc/fstab"

if [ -n "$YUM" ]; then
    # install all built RPMs
    sudo chroot "$chroot_dir" bash -c -l "$YUM install --verbose --debuglevel=10 -y /tmp/qubes-packages-mirror-repo/rpm/*.rpm"
fi

APT="$(sudo chroot "$chroot_dir" /usr/bin/which apt-get || true)"
if [ "$APT" ]; then
    # install all built DEBs
    PKGS="$(sudo chroot "$chroot_dir" bash -c -l 'find /tmp/qubes-deb -type f -name "*.deb"' | tr '\n' ' ')"
    sudo chroot "$chroot_dir" bash -c -l "DEBIAN_FRONTEND=noninteractive DEBCONF_NOWARNINGS=yes DEBIAN_PRIORITY=critical apt-get -o Dpkg::Options::=--force-confnew --yes install $PKGS"
fi
